package model

import (
	"errors"
	"gorm.io/gorm"
)

type (
	CompanyMode struct {
		db *gorm.DB
	}

	Company struct {
		Model
		Name    string `json:"name" gorm:"type:varchar(255)"`
		IconImg string `json:"icon_img" gorm:"type:varchar(255)"`
		Remarks string `json:"remarks" gorm:"type:varchar(255)"`
		GroupId int64  `json:"group_id" gorm:"default:0"`
	}
)

func NewCompanyMode(db *gorm.DB) *CompanyMode {
	return &CompanyMode{
		db: db,
	}
}

func (m *CompanyMode) Add(data *Company) error {
	return m.db.Create(data).Error
}

func (m *CompanyMode) Del(id int64) (int64, error) {
	tx := m.db.Where("id = ?", id).Delete(&Company{})
	return tx.RowsAffected, tx.Error
}
func (m *CompanyMode) Get(id int64) (Company, error) {
	var company Company
	tx := m.db.Where("id = ?", id).First(&company)
	return company, tx.Error
}

func (m *CompanyMode) Update(id int64, data *Company) (int64, error) {
	tx := m.db.Where("id = ?", id).Updates(data)
	return tx.RowsAffected, tx.Error
}

func (m *CompanyMode) FindCount() (int64, error) {
	var number int64
	err := m.db.Model(&Company{}).Count(&number).Error
	if err != nil {
		return number, err
	}
	return number, nil
}

func (m *CompanyMode) FindList(page, size int) ([]Company, error) {
	list := make([]Company, 0, 1)
	dbSession := m.db.Limit(size).Offset((page - 1) * size)
	err := dbSession.Find(&list).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return list, nil
	} else if err != nil {
		return list, err
	}
	return list, nil
}
